<?php

namespace App\Api\Controllers;

use App\Http\Controllers\Controller;
use App\Models\SmsCode;
use App\Models\User;
use Dingo\Api\Exception\StoreResourceFailedException;
use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class RegisterController extends Controller
{
    use RegistersUsers;
    use Helpers;
    const SmsExpire=1500;//验证码有效期

    public function register(Request $request){

        $validator = $this->validator($request->all());
        if($validator->fails()){
            throw new StoreResourceFailedException("Validation Error", $validator->errors());
        }
        if($this->checkSmsCode($request->all())){
            return $this->response()->error("注册失败，验证码失效", 200);
        }

        $user = $this->create($request->all());

        if($user){

            $token = JWTAuth::fromUser($user);

            return $this->response()->array([
                "token" => $token,
                "message" => "注册成功",
                "status_code" => 201
            ]);
        }else{
            return $this->response()->error("注册失败", 200);
        }
    }

    /**
     * @return bool
     * 检查短信验证码
     */
    protected function checkSmsCode($data){
        if(strlen($data['phone_number']==11) && strlen($data['sms_code'])>=4){
            $code=SmsCode::where([['phone_number',$data['phone_number']],['sms_code',$data['sms_code']],['ctime','>',time()-self::SmsExpire],['status',0]])->first();
            if($code){
                $code->status=1;
                $code->save();
                return true;
            }
            return false;
        }else{
            return false;
        }
        return true;
    }
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'phone_number' => 'required',
            'sms_code' => 'required|min:4',
            'password' => 'required|min:6',
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'phone_number' => $data['phone_number'],
            'call_phone' => $data['phone_number'],
            'name'=>'rm_'.$data['phone_number'],
            'password' => bcrypt($data['password']),
        ]);
    }

    /**
     * 发送短信验证码
     * @param Request $request
     * @return mixed
     */
    public function smsCode(Request $request){
        $phoneNumber=$request->input('phone_number');
        if($phoneNumber && strlen($phoneNumber)==11){
            //检查电话号码是否已被注册。
            $checkNum=$this->checkPhoneNumber($phoneNumber);
            if($checkNum){
                return $this->response()->array([
                    "message" => "手机号码已被注册",
                    "status_code" => 200
                ]);
            }
            //先在数据库查询是否存在90秒内，该电话号码未被使用的短信验证码，
            $code=SmsCode::where([['phone_number',$phoneNumber],['ctime','>',time()-self::SmsExpire],['status',0]])->first();
            if($code){
                $smsCode=$code->code;
                $code->ctime=time();
                $code->save();
            }else{
                //生成一个验证码
                $smsCode=random_int(1000,9999);
                SmsCode::create([
                    'phone_number'=>$phoneNumber,
                    'ctime'=>time(),
                    'code'=>$smsCode,
                    'status'=>0
                ]);
            }
            return $this->response()->array([
                "message" => "短信已发送",
                'sms_code'=>$smsCode,
                "status_code" => 201
            ]);
        }else{
            return $this->response()->array([
                "message" => "请求不合法",
                "status_code" => 403
            ]);
        }
    }
    /**
     * 检测手机号是否被注册
     */
    public function checkPhoneNumber($phoneNumber){
        $user=User::where('phone_number',$phoneNumber)->first();
        return $user?true:false;
        /*if($user){
            return $this->response()->array([
                "message" => "手机号已被注册",
                "result"=>true,
                "status_code" => 200
            ]);
        }else{
            return $this->response()->array([
                "message" => "手机号未被注册",
                "result"=>false,
                "status_code" => 200
            ]);
        }*/
    }

}